package com.chris.utils;

import com.chris.model.ResultMsg;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

public class ResponseUtil {
    /**
     * 生成并返回JSON格式的响应
     *
     * @param response HttpServletResponse对象
     */
    public static void result(HttpServletResponse response, ResultMsg resultMsg) {
        // 设置响应内容类型为JSON
        response.setContentType("application/json;charset=UTF-8");

        // 创建响应数据的Map
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("code", resultMsg.getCode());
        resultMap.put("msg", resultMsg.getMsg());
        resultMap.put("data", resultMsg.getData());

        // 使用Jackson库将Map转换为JSON字符串
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonResponse;
        try {
            jsonResponse = objectMapper.writeValueAsString(resultMap);
        } catch (Exception e) {
            throw new RuntimeException("Failed to convert response to JSON", e);
        }

        // 将JSON字符串写入响应
        try (PrintWriter out = response.getWriter()) {
            out.print(jsonResponse);
            out.flush();
        } catch (IOException e) {
            throw new RuntimeException("Failed to write response", e);
        }
    }
}
